﻿using _15Net8AspNetCore_ORM.Context;
using _15Net8AspNetCore_ORM.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace _15Net8AspNetCore_ORM.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        public EFCoreDBContext _EFCoreDB { get; set; }
        public ProductController(EFCoreDBContext eFCoreDB)
        {
            _EFCoreDB = eFCoreDB;
        }


        /// <summary>
        /// 新增商品
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> AddProduct(Product product)
        {
            await _EFCoreDB.Products.AddAsync(product);
            await _EFCoreDB.SaveChangesAsync();
            return CreatedAtAction(nameof(GetProduct), new { id = product.ID }, product);
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        [HttpDelete]
        public async Task<IActionResult> DeleteProduct(Product product)
        {
            _EFCoreDB.Products.Remove(product);
            await _EFCoreDB.SaveChangesAsync();
            return Ok("删除成功");
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        [HttpDelete("id")]
        public async Task<IActionResult> DeleteProduct(int id)
        {
            Product product = await _EFCoreDB.Products.FirstOrDefaultAsync(T => T.ID == id);
            if (product != null)
            {
                _EFCoreDB.Products.Remove(product);
                await _EFCoreDB.SaveChangesAsync();
                return Ok("删除成功");
            }
            else
            {
                return NotFound();
            }   
        }

        /// <summary>
        /// 修改商品
        /// </summary>
        [HttpPut("id")]
        public async Task<IActionResult> UpdateProduct(int id, Product product)
        {

            //1、设置更新状态
            _EFCoreDB.Entry(product).State = EntityState.Modified;
            try
            {
                await _EFCoreDB.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw;
            }            
            return Ok("更新成功");
        }

        /// <summary>
        /// 获取商品
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetProduct()
        {
            List<Product> products = await _EFCoreDB.Products.Include(p => p.Images).ToListAsync();
            return Ok(products);
        }

        /// <summary>
        /// 获取商品
        /// </summary>
        [HttpGet("id")]
        public async Task<IActionResult> GetProduct(int id)
        {
            Product product = await _EFCoreDB.Products.Include(p => p.Images).FirstOrDefaultAsync(T => T.ID == id);
            return Ok(product);
        }
    }
}
